package com.qf.listener;

import com.qf.constans.SystemParameter;
import com.qf.feign.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;

@Component

public class MyRabbitMQListener {

    Logger logger = LoggerFactory.getLogger(MyContextLoadlistener.class);
    @Resource
    private MySubMessageChannel channel;
    @Resource
    private RedisService redisService;


    //方法一：
//    @StreamListener("1907apiupdate")//声明接收这个的
    public void onMessage(String message) {
        System.err.println("收到了消息:" + message);

        Set<String> keys = redisService.keys(SystemParameter.REDISAPIPRE + "*");

        SystemParameter.apiinfoMap.clear();

        for (String key : keys) {

            Map<Object, Object> map = redisService.hgetAll(key);
            SystemParameter.apiinfoMap.put(key,map);
        }
        logger.error("初始化api信息,得到的结果是:{}", SystemParameter.apiinfoMap);
    }

    //方法二:
    @PostConstruct   //构造方法完成后执行
    public void init(){
        channel.CHANNEL().subscribe(new MessageHandler() {
            @Override
            public void handleMessage(Message<?> message) throws MessagingException {


                String payload = new String((byte[]) message.getPayload());
                System.err.println("收到了消息:" + payload);

                Set<String> keys = redisService.keys(SystemParameter.REDISAPIPRE + "*");
                SystemParameter.apiinfoMap.clear();
                for (String key : keys) {
                    Map<Object, Object> map = redisService.hgetAll(key);
                    SystemParameter.apiinfoMap.put(key,map);
                }
                logger.error("初始化api信息,得到的结果是:{}", SystemParameter.apiinfoMap);
            }
        });
    }

}
